#include <54func.h>
//实现同步机制，A写B读
typedef struct shareRes_s
{
    int fd;
    bool flag;
    pthread_mutex_t mutex;

}shareRes_t;
void *threadFunc(void *arg)
{
    shareRes_t * pshareRes = (shareRes_t *)arg;
    char buf[4096] = {0};
    while(1)
    {
        if(pshareRes->flag)//如果a已经写入数据
        {
            //主线程与子线程读写共享同一个文件，因此文件偏移量也是共享的!!!!!!
            lseek(pshareRes->fd,0,SEEK_SET);
            pthread_mutex_lock(&pshareRes->mutex);
            read(pshareRes->fd,buf,sizeof(buf));
            pthread_mutex_unlock(&pshareRes->mutex);
            printf("I am child!buf = %s\n",buf);
            break;
        }
    }

    pthread_exit(NULL);
}
int main(int argc,char *argv[])
{
    // ./0_homework file
    ARGS_CHECK(argc,2);

    //设置标志位，用于表示主线程写完毕
    shareRes_t shareRes;
    shareRes.flag = false;//初始化标志位
    
    shareRes.fd = open(argv[1],O_RDWR);
    ERROR_CHECK(shareRes.fd,-1,"open");

    pthread_mutex_init(&shareRes.mutex,NULL);//锁初始化
    pthread_t tid;//获取子线程tid
    pthread_create(&tid,NULL,threadFunc,&shareRes);//创建子线程
    //主线程写入数据
    pthread_mutex_lock(&shareRes.mutex);//加锁    
    write(shareRes.fd,"hello",5);
    shareRes.flag = true;//A已经再文本中写入数据才将该标志位转换为true
    pthread_mutex_unlock(&shareRes.mutex);//解锁
    
    printf("write over!\n");

    pthread_join(tid,NULL);//回收子线程资源
    close(shareRes.fd);
    return 0;
}
